﻿using System;
using System.Linq;
using System.Windows.Data;
using ForumsBrowser.BusinessObjects;

namespace ForumsBrowser
{
    public class ThreadToAnswerTextFormatter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string result = string.Empty;
            if (value != null)
            {            
            if (!(value is Thread)) throw new NotSupportedException("Wrong Type!");

            Thread t = value as Thread;

                var answerers = t.Messages.Where(m => m.Answer).Select(m => m.Author.DisplayName).Distinct().ToArray();
                if (answerers.Length > 1)
                    result = string.Format("Answered by {0} and {1}", string.Join(", ", answerers.Take(answerers.Length - 1).ToArray()), answerers.Last());
                else if (answerers.Length == 1)
                    result = string.Format("Answered by {0}", answerers.Last());
            }

            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
